package com.chuangsi.framework.config.easyexcel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.chuangsi.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author: lq
 * @Date: 2021/1/14
 */
@Slf4j
public class UploadDataListener<T> extends AnalysisEventListener<T> {

    private final List<T> data = new ArrayList<>();

    private Map<Integer, String> headMap;

    @Override
    public void invoke(T d, AnalysisContext context) {
        data.add(d);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        this.setHeadMap(headMap);
    }

    @Override
    public void onException(Exception exception, AnalysisContext context) {
        if (exception instanceof ExcelDataConvertException) {
            ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException)exception;
            throw new ServiceException("第"+(excelDataConvertException.getRowIndex()+1)+"行【"
                    + this.getHeadMap().get( excelDataConvertException.getColumnIndex())
                    +"】解析异常,值【"+excelDataConvertException.getCellData()+"】");
        }
    }

    public List<T> getData() {
        return data;
    }

    public Map<Integer, String> getHeadMap() {
        return headMap;
    }

    public void setHeadMap(Map<Integer, String> headMap) {
        this.headMap = headMap;
    }
}
